package com.yuanian.springbootProject.controller;

import com.yuanian.springbootProject.dto.ResponseResult;
import com.yuanian.springbootProject.entity.TUser;
import com.yuanian.springbootProject.service.IUserService;
import com.yuanian.springbootProject.util.Utils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    private IUserService userService;

    /**
     * 插入一个用户
     * @param user 用户数据
     * @return
     */
    @PostMapping("one")
    public ResponseResult insertOne(@RequestBody TUser user){
        user.setUserId(Utils.getRandomUUID());
        user.setCreateDate(new Date());
        user.setUpdateDate(new Date());
        int i = userService.insert(user);
        if (i > 0) return ResponseResult.ok();
        else return ResponseResult.fail();
    }

    /**
     * 根据id删除一个用户
     * @param id
     * @return
     */
    @DeleteMapping("one/{id}")
    public ResponseResult deleteByID(@PathVariable String id){
        if (userService.deleteUserAndRelationByPrimaryKey(id)>0) return ResponseResult.ok();
        return ResponseResult.fail();
    }

    /**
     * 更新一个用户
     * @param user
     * @return
     */
    @PutMapping("one")
    public ResponseResult updateOne(@RequestBody TUser user){
        if (userService.updateByPrimaryKeySelective(user)>0) return ResponseResult.ok();
        return ResponseResult.fail();
    }

    /**
     * 根据id查找一个用户
     * @param id
     * @return
     */
    @GetMapping("one/{id}")
    public ResponseResult getOneById(@PathVariable("id") String id){
        return ResponseResult.ok(userService.selectByPrimaryKey(id));
    }

    /**
     * 查找所有用户
     * @return
     */
    @GetMapping("all")
    public ResponseResult getAll(){
        return ResponseResult.ok(userService.selectAll());
    }
}
